package com.cuicui.mall.service;

import com.cuicui.mall.dao.GoodsDataMapper;
import com.cuicui.mall.entity.GoodsData;
import com.cuicui.mall.entity.GoodsDataExample;
import com.cuicui.mall.utils.CommonResponse;
import com.cuicui.mall.vo.GoodsVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsService {
    @Autowired
    private GoodsDataMapper goodsDataDao;

    public CommonResponse getPage (Integer pageNO, Integer pageSize) {
        GoodsDataExample goodsDataExample = new GoodsDataExample();
        GoodsDataExample.Criteria criteria = goodsDataExample.createCriteria();
        PageHelper.startPage(pageNO, pageSize);

        List<GoodsData> goodsDataList = goodsDataDao.selectByExample(goodsDataExample);
        List<GoodsVO> goodsVOList = goodsDataList.stream().map((goodsDataItem)->{
            GoodsVO goodsVO = new GoodsVO();
            BeanUtils.copyProperties(goodsDataItem, goodsVO);
            return goodsVO;
        }).collect(Collectors.toList());

        PageInfo<GoodsVO> pageInfo = new PageInfo<>();
        pageInfo.setList(goodsVOList);
        return CommonResponse.success(pageInfo);
    }

    public CommonResponse add (GoodsVO goodsVO) {
        GoodsData goodsData = new GoodsData();
        BeanUtils.copyProperties(goodsVO, goodsData);
        try{
            goodsDataDao.insert(goodsData);
        }catch (Exception e){
            return  CommonResponse.error("500", "添加失败");
        }
        return CommonResponse.success(true);
    }


    public CommonResponse remove (Integer id) {
        try{
            goodsDataDao.deleteByPrimaryKey(id);
        }catch (Exception e){
            return CommonResponse.error("500", "删除失败");
        }
        return CommonResponse.success(true);
    }
}
